﻿using System;
using System.Collections.Generic;
using NHibernate;
using OrderCreator.NHibernate.DataModel.Domain;

namespace OrderCreator.NHibernate.DataModel.Repositories
{
    public class ProductRepository : IProductRepository
    {
        #region Implementation of IProductRepository

        public void Add(Product product)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(product);
                    transaction.Commit();
                }
            }
        }

        public void Update(Product product)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Update(product);
                    transaction.Commit();
                }
            }
        }

        public void Remove(Product product)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(product);
                    transaction.Commit();
                }
            }
        }

        public Product GetProductById(Guid id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                return session.Get<Product>(id);
            }
        }

        public IList<Product> GetAllProducts()
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                return session.CreateCriteria(typeof (Product)).List<Product>();
            }
        }

        #endregion
    }
}
